package activity.workflow;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.*;
import org.activiti.engine.form.TaskFormData;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ModelQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 流程模型控制器
 *
 * @author wangkang
 */
@Controller
@RequestMapping("workflow")
public class ModelController {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    RepositoryService repositoryService;

    @Resource
    private HistoryService historyService;

    @Resource
    private RuntimeService runtimeService;

    @Resource
    private IdentityService identityService;

    @Resource
    private FormService formService;

    /**
     * 模型列表
     */
    @RequestMapping("list")
    public ModelAndView modelList() {
        ModelAndView mav = new ModelAndView("workflow/model-list");
        List<Model> list = repositoryService.createModelQuery().list();
        mav.addObject("list", list);
        return mav;
    }

    @GetMapping(value = "findByPage")
    @ResponseBody
    public Object findByPage(@RequestParam(value = "page", required = false, defaultValue = "1") Integer pageNum,
                             @RequestParam(value = "rows", required = false, defaultValue = "10") Integer rows,
                             @RequestParam(value = "keyWord", required = false) String keyWord) {
        Grid<Model> grid = new Grid<>();
        try {
            String orgCode = null;
            int pageSize = rows;
            int firstNum = (pageNum - 1) * pageSize;
            ModelQuery modelQuery = repositoryService.createModelQuery();
            List<Model> list;
            if (!StringUtils.isNotBlank(keyWord) && StringUtils.isNoneBlank(orgCode)) {
                list = modelQuery.modelCategoryLike(orgCode).orderByCreateTime().desc()
                        .listPage(firstNum, pageSize);
            } else if (StringUtils.isNotBlank(keyWord) && StringUtils.isNoneBlank(orgCode)) {
                list = modelQuery.modelNameLike("%" + keyWord + "%").modelCategoryLike(orgCode)
                        .orderByCreateTime().desc().listPage(firstNum, pageSize);
            } else {
                list = modelQuery.orderByCreateTime().desc().listPage(firstNum, pageSize);
            }
            long count = modelQuery.count();
            grid.setRows(list);
            grid.setTotal(count);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return grid;
    }

    /**
     * 创建模型
     */
    @GetMapping("create")
    public void create(@RequestParam(value = "name", required = false) String name,
                       @RequestParam(value = "key", required = false) String key,
                       @RequestParam(value = "description", required = false) String description,
                       HttpServletRequest request,
                       HttpServletResponse response) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            ObjectNode editorNode = objectMapper.createObjectNode();
            editorNode.put("id", "canvas");
            editorNode.put("resourceId", "canvas");
            ObjectNode stencilSetNode = objectMapper.createObjectNode();
            stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
            editorNode.put("stencilset", stencilSetNode);
            Model modelData = repositoryService.newModel();

            ObjectNode modelObjectNode = objectMapper.createObjectNode();
            modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, StringUtils.defaultString(name, "自定义名称"));
            modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, 1);
            description = StringUtils.defaultString(description, "流程描述");
            modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, description);
            modelData.setMetaInfo(modelObjectNode.toString());
            modelData.setName(name);
            modelData.setKey(StringUtils.defaultString(key, "自定义key"));
            repositoryService.saveModel(modelData);
            System.out.println("保存模型信息:" + modelData);
            repositoryService.addModelEditorSource(modelData.getId(), editorNode.toString().getBytes(StandardCharsets.UTF_8));
            response.sendRedirect(request.getContextPath() + "/process/modeler.html?modelId=" + modelData.getId());
        } catch (Exception e) {
            logger.error("创建模型失败：", e);
        }
    }

    /**
     * 根据Model部署流程
     */
    @RequestMapping(value = "deploy/{modelId}")
    @ResponseBody
    public Object deploy(@PathVariable("modelId") String modelId) {
        ResponseBean responseBean = new ResponseBean();
        try {
            Model modelData = repositoryService.getModel(modelId);
            ObjectNode modelNode = (ObjectNode) new ObjectMapper().readTree(repositoryService.getModelEditorSource(modelData.getId()));
            byte[] bpmnBytes = null;

            BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);
            bpmnBytes = new BpmnXMLConverter().convertToXML(model);

            String processName = modelData.getName() + ".bpmn20.xml";
            //Deployment deployment = repositoryService.createDeployment().name(modelData.getName()).addString(processName, new String(bpmnBytes)).deploy();
            Deployment deployment = repositoryService.createDeployment().name(modelData.getName()).category(modelData.getCategory())
                    .addString(processName, new String(bpmnBytes, StandardCharsets.UTF_8)).deploy();
            System.out.println("部署成功，部署ID=" + deployment.getId());
            responseBean.setSuccess(true);
            responseBean.setMsg("部署成功，部署ID=" + deployment.getId());
        } catch (Exception e) {
            responseBean.setSuccess(false);
            responseBean.setMsg(modelId + "根据模型部署流程失败:" + e);
            logger.error("根据模型部署流程失败：modelId={}", modelId, e);
        }
        return responseBean;
    }

    /**
     * 导出model对象为指定类型
     *
     * @param modelId 模型ID
     * @param type    导出文件类型(bpmn\json)
     */
    @RequestMapping(value = "export/{modelId}/{type}")
    public void export(@PathVariable("modelId") String modelId,
                       @PathVariable("type") String type,
                       HttpServletResponse response) {
        try {
            Model modelData = repositoryService.getModel(modelId);
            BpmnJsonConverter jsonConverter = new BpmnJsonConverter();
            byte[] modelEditorSource = repositoryService.getModelEditorSource(modelData.getId());

            JsonNode editorNode = new ObjectMapper().readTree(modelEditorSource);
            BpmnModel bpmnModel = jsonConverter.convertToBpmnModel(editorNode);

            // 处理异常
            if (bpmnModel.getMainProcess() == null) {
                response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value());
                response.getOutputStream().println("no main process, can't export for type: " + type);
                response.flushBuffer();
                return;
            }
            String filename = "";
            byte[] exportBytes = null;
            String mainProcessId = bpmnModel.getMainProcess().getId();
            if (type.equals("bpmn")) {
                BpmnXMLConverter xmlConverter = new BpmnXMLConverter();
                exportBytes = xmlConverter.convertToXML(bpmnModel);
                filename = mainProcessId + ".bpmn20.xml";
            } else if (type.equals("json")) {
                //处理乱码
                String result = new String(modelEditorSource, StandardCharsets.UTF_8);
                exportBytes = result.getBytes();
                //exportBytes = modelEditorSource;
                filename = mainProcessId + ".json";
            }
            ByteArrayInputStream in = new ByteArrayInputStream(exportBytes);
            IOUtils.copy(in, response.getOutputStream());
            response.setHeader("Content-Disposition", "attachment; filename=" + filename);
            response.flushBuffer();
        } catch (Exception e) {
            logger.error("导出model的xml文件失败：modelId={}, type={}", modelId, type, e);
        }
    }


    /**
     * 流程图路径获取接口
     */
    @RequestMapping("getImgPath")
    public void viewHistory(@RequestParam("flowId") String flowId,
                            HttpServletRequest request,
                            HttpServletResponse response) {
        try {
            HistoricProcessInstance instance = historyService
                    .createHistoricProcessInstanceQuery()
                    .processInstanceId(flowId)
                    .singleResult();
            response.sendRedirect(request.getContextPath()
                    + "/process/diagram-viewer/index.html?processDefinitionId="
                    + instance.getProcessDefinitionId() + "&processInstanceId=" + flowId);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
    }

    /**
     * 流程图路径获取接口
     */
    @RequestMapping("getForm")
    @ResponseBody
    public Object getForm(String processDefinitionId) {
        ResponseBean responseBean = new ResponseBean();
        try {
            //StartFormData startFormData = formService.getStartFormData(processDefinitionId);
            TaskFormData taskFormData = formService.getTaskFormData(processDefinitionId);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return responseBean;
    }

    /**
     * 编辑模型
     */
    @RequestMapping(value = "edit")
    public void edit(String modelId, HttpServletRequest request, HttpServletResponse response) {
        try {
            response.sendRedirect(request.getContextPath() + "/process/modeler.html?modelId=" + modelId);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
    }


    @RequestMapping(value = "delete/{modelId}")
    public String delete(@PathVariable("modelId") String modelId) {
        repositoryService.deleteModel(modelId);
        return "redirect:/workflow/model/list";
    }


    /**
     * 启动流程
     */
    @RequestMapping("start")
    @ResponseBody
    public Object startWorkflow(String modelId, String userIds) {
        ResponseBean responseBean = new ResponseBean();
        try {
            Map<String, Object> map = new HashMap<>(3);
            map.put("userIds", userIds);
            // 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
            //identityService.setAuthenticatedUserId("wangkang");
            ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(modelId, map);
            responseBean.setSuccess(true);
            responseBean.setMsg("流程已启动，流程ID：" + processInstance.getId()
                    + "，流程定义的ID：" + processInstance.getProcessDefinitionId());
        } catch (ActivitiException e) {
            if (e.getMessage().contains("no processes deployed with key")) {
                logger.warn("没有部署流程!", e);
                responseBean.setMsg("没有部署流程，请在[工作流]->[流程管理]页面点击<重新部署流程>");
            } else {
                logger.error("启动流程失败：", e);
                responseBean.setMsg("启动流程失败：系统内部错误！");
            }
        } catch (Exception e) {
            logger.error("启动流程失败：", e);
            responseBean.setMsg("启动流程失败：系统内部错误！");
        }
        return responseBean;
    }
}
